package quest.handler
{
import core.model.GameModel;

import quest.IQuestManager;

import values.item.ItemTemplateValue;
import values.quest.QuestGoalValue;

public class QuestResourceItemCollectGoalHandler extends QuestGoalHandlerBase
{
	public function QuestResourceItemCollectGoalHandler(manager:IQuestManager)
	{
		super(manager);
	}
	
	override public function get key():String
	{
		return "collect_resource";
	}
	
	override public function addTargetQuestGoal(goal:QuestGoalValue):void
	{
		super.addTargetQuestGoal(goal);
		goal.params.itemKey = goal.template.params.split(":")[0];
		goal.params.needNum = goal.template.params.split(":")[1];
		
		var history:Number = 0;
		if (goal.params.hasOwnProperty("currentNum"))
		{
			history = goal.params.currentNum;
		}
		else
		{
			if (goal.template.conditionObj.readHistory == true)
			{
				history = NaN;
			}
		}
		updateProgressString(goal, history);
	}
	
	override protected function checkGoal(goal:QuestGoalValue, type:String, ...args):void
	{		
		var template:ItemTemplateValue = args[0];		
		var count:Number = args[1];
		//quest progress
		if (goal.params.itemKey == template.key)
		{
			manager.questProgress(goal.owner);
			
			var history:Number = NaN;
			if (goal.template.conditionObj.readHistory == false)
			{
				history = goal.params.currentNum + count;
			}
			updateProgressString(goal, history);
			
			//quest goal complete
			if (goal.params.currentNum >= goal.params.needNum)
			{
				goal.isCompleted = true;
				manager.questGoalComplete(goal);
			}
		}
	}
	
	protected function updateProgressString(goal:QuestGoalValue, history:Number = NaN):void
	{
		var current:Number = 0;
		if (isNaN(history))
		{
			current = GameModel.instance.playerModel.getItemNum(goal.params.itemKey);
		}
		else
		{
			current = history;
		}
		goal.params.currentNum = current;
		
		goal.progressString = goal.params.currentNum + " / " + goal.params.needNum;
	}
}
}